#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //设置根结点的标题, 仅用于描述各列数据的含义，不会作为独立的结点存在
    ui->treeWidget->setHeaderLabel("动物");
    //ui->treeWidget->setColumnCount(2);

    //创建顶层结点
    QTreeWidgetItem* item1=new QTreeWidgetItem;
    //在第一列中进行设置(可以设置不止一列)
    item1->setText(0,"狗");
    //将顶层结点进行添加
    ui->treeWidget->addTopLevelItem(item1);

   QTreeWidgetItem* item2=new QTreeWidgetItem;
   item2->setText(0,"猫");
   ui->treeWidget->addTopLevelItem(item2);

   QTreeWidgetItem* item3=new QTreeWidgetItem;
   item3->setText(0,"鸟");
   item3->setText(1,"乌龟");
   ui->treeWidget->addTopLevelItem(item3);


   //添加子结点
   // 创建子结点
   QTreeWidgetItem* child_item1=new QTreeWidgetItem;
   //在第一列中进行设置
   child_item1->setText(0,"哈士奇");
   //child_item1->setText(1,"金毛");
    //进行添加子结点
   item1->addChild(child_item1);

   QTreeWidgetItem* child_item2=new QTreeWidgetItem;
   child_item1->setText(0,"金毛");
   item1->addChild(child_item2);

   QTreeWidgetItem* child_item3=new QTreeWidgetItem;
   child_item3->setText(0,"三花");
   item2->addChild(child_item3);





}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_addTop_clicked()
{
    //创建新顶层结点
    QTreeWidgetItem*topItem=new QTreeWidgetItem;
    //获取顶层结点命名
   const QString str(ui->lineEdit->text());
    //进行设置
    topItem->setText(0,str);
    //进行添加
   ui->treeWidget->addTopLevelItem(topItem);
}

void Widget::on_pushButton_addSelect_clicked()
{
    //获取当前选中的结点
    QTreeWidgetItem* current=ui->treeWidget->currentItem();
    if(current==nullptr)
    {
        return;
    }
    //创建新结点
    QTreeWidgetItem* item=new QTreeWidgetItem;
    //获取文本
    const QString str(ui->lineEdit->text());
    //对结点进行设置
    item->setText(0,str);
    //进行设置子结点
   current->addChild(item);

}

void Widget::on_pushButton_deleteSelect_clicked()
{
    //找到当前结点
     QTreeWidgetItem* current=ui->treeWidget->currentItem();
     if(current==nullptr)
     {
         return;
     }
     //分别对顶层结点和子结点进行处理
     QTreeWidgetItem* parent=current->parent();
     if(parent==nullptr)
     {
         //顶层结点
         int index=ui->treeWidget->indexOfTopLevelItem(current);
         ui->treeWidget->takeTopLevelItem(index);

     }
     else
     {
         //子结点
         parent->removeChild(current);
     }





}
